package com.hxzy.controller.admin;

import com.hxzy.dto.GoodsCategoryDTO;
import com.hxzy.entity.TbNewbeeMallGoodsCategory;
import com.hxzy.service.TbNewbeeMallGoodsCategoryService;
import com.hxzy.vo.ResultEnum;
import com.hxzy.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;

@Controller
@RequestMapping(value = "/admin")
public class GoodsCategoryController {
    @Autowired
    private TbNewbeeMallGoodsCategoryService goodsCategoryService;


    @GetMapping(value = "/categories")
    private ModelAndView search(GoodsCategoryDTO goodsCategoryDTO){
        ModelAndView mv=new ModelAndView();

        mv.setViewName("admin/goods_category");

        mv.addObject("path","categories");
        mv.addObject("data",goodsCategoryDTO);
        return mv;
    }

    @ResponseBody
    @GetMapping(value = "/categories/data")
    public ResultVO ajaxData(GoodsCategoryDTO goodsCategoryDTO){
        return ResultVO.success(this.goodsCategoryService.search(goodsCategoryDTO));
    }

    @ResponseBody
    @PostMapping(value = "/categories/save")
    public ResultVO addOrUpdate(@Valid TbNewbeeMallGoodsCategory tbNewbeeMallGoodsCategory, BindingResult bindingResult){
        if (bindingResult.getFieldErrorCount()>0){
            String msg = bindingResult.getFieldErrors().get(0).getDefaultMessage();
            ResultVO failed = ResultVO.failed(ResultEnum.PARAMS_FAILED);
            failed.setMessage(msg);
            return failed;
        }

        return this.goodsCategoryService.addOrUpdate(tbNewbeeMallGoodsCategory);
    }

    @ResponseBody
    @GetMapping(value = "/categories/threelevel")
    private ResultVO threeLevelCategory(){
        return this.goodsCategoryService.searchAll();
    }
}
